import Vue from 'vue'
import Vuex from 'vuex'
import Cookies from 'js-cookie'
import _axios from '@/plugins/axios.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token:null,
    userInfo:null,
    userOrder:null//
  },
  getters:{
    logintoken(state){
      if(state.token==null || state.token.length<1){
        state.token=Cookies.get('token');
        if(!state.token){
          state.token=localStorage.getItem('token');
        }
      }
      return state.token;
    },
    loginuser(state){
      if(!state.userInfo || !state.userInfo.id){
        state.userInfo=JSON.parse(localStorage.getItem('user_info'))
      }
      return state.userInfo;
    },
    //
    logorder(state){
      if(!state.userOrder || !state.userOrder.id){
        state.userOrder=JSON.parse(localStorage.getItem('user_order'))
      }
      return state.userOrder;
    }
  },
  mutations: {
    saveToken(state,payload){
      state.token=payload;
      //存token到cookie里面
      Cookies.set("token",payload,{expires:0.5});
      localStorage.setItem('token',payload);
    },
    loginout(state){
      state.token=null;
      Cookies.remove('token');
      localStorage.removeItem('token');
    },
    saveuserInfo(state,payload){
      state.userInfo=payload;
      localStorage.setItem('user_info',JSON.stringify(payload));
    },
    //
    saveuserOrder(state,payload){
      state.userOrder=payload;
      localStorage.setItem('user_order',JSON.stringify(payload));
    }
  },
  actions: {
    getuserInfo(context){
      _axios.get('/user',{
        headers:{
          "Authori-zation": "Bearer "+context.state.token
        }
      }).then(result=>{
        context.commit('saveuserInfo',result);
      });
    },
    //
    getuserOrder(context){
      _axios.get('/menu/user',{
        headers:{
          "Authori-zation": "Bearer "+context.state.token
        }
      }).then(result=>{
        context.commit('saveuserOrder',result);
      });
    }
  },
  modules: {
  }
})
